package com.jrx.anytxn.param.service.rights.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrRightsAndInterestsReq;
import com.jrx.anytxn.param.entity.PrRightsAndInterestsRes;
import com.jrx.anytxn.param.entity.PrRightsAndInterests;
import com.jrx.anytxn.param.enums.EnableTagEnum;
import com.jrx.anytxn.param.mapper.ext.ExtPrRightsAndInterestsMapper;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 对账文件参数service实现
 */
@CacheConfig(cacheNames = "RIGHTS")
@Service
public class PrRightsAndInterestsServiceImpl implements IPrRightsAndInterestsService {

    private static final Logger logger = LoggerFactory.getLogger(PrRightsAndInterestsServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtPrRightsAndInterestsMapper extPrRightsAndInterestsMapper;

    @Override
    public PrRightsAndInterestsRes getByTenIdIdAndRightsId(String tenantId, String rightsId) throws TxnException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(rightsId)) {
            logger.error("商户ID或权益ID为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        PrRightsAndInterests prRightsAndInterests = extPrRightsAndInterestsMapper.selectByRightsIdAndTenantId(rightsId,tenantId);
        if (null == prRightsAndInterests) {
            logger.error("未查到权益参数信息");
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        return BeanMapping.copy(prRightsAndInterests, PrRightsAndInterestsRes.class);
    }

    @Override
    public Integer addPrRightsAndInterests(PrRightsAndInterestsReq prRightsAndInterestsReq) throws TxnException {
        int res = 0;

        PrRightsAndInterests prRightsAndInterests = BeanMapping.copy(prRightsAndInterestsReq, PrRightsAndInterests.class);
        prRightsAndInterests.setCreateTime(new Date());
        prRightsAndInterests.setUpdateTime(new Date());

        String rightsId = prRightsAndInterestsReq.getRightsId();
        if (StringUtils.isBlank(rightsId)) {
            rightsId =  System.currentTimeMillis() + "";
            rightsId = rightsId + (int)((Math.random() * 9 + 1) * 10000);
        }
        logger.info("添加权益记录, rightsId: {}", rightsId);
        prRightsAndInterests.setRightsId(rightsId);

        try {
            prRightsAndInterests.setId(segmentService.getId(Constant.PR_RIGHTS_AND_INTERESTS_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        prRightsAndInterests.setRecordVersionNumber(Constant.VERSION_NUMBER);
        return res = extPrRightsAndInterestsMapper.insertSelective(prRightsAndInterests);
    }

    @Override
    public List<PrRightsAndInterestsRes> findAllByTenId(String tenantId) {
        List<PrRightsAndInterests> list = extPrRightsAndInterestsMapper.selectByTenIdAndStatus(tenantId);
        return BeanMapping.copyList(list, PrRightsAndInterestsRes.class);
    }

    @Override
    public TxnPage<PrRightsAndInterestsRes> findAllPageByCondition(Integer pageNum, Integer pageSize, PrRightsAndInterestsReq req) throws TxnException {
        Page<PrRightsAndInterestsRes> page = PageHelper.startPage(pageNum, pageSize, Constant.ORDER_BY_SORT);
        List<PrRightsAndInterests> tableList = extPrRightsAndInterestsMapper.queryByPrRightsAndInterestsReq(req);
        if (CollectionUtils.isEmpty(tableList)) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        List<PrRightsAndInterests> newTableList = new ArrayList<>();
        //展示调整
        for(PrRightsAndInterests prRightsAndInterests : tableList){
            if (Constant.RIGHTS_TYPE_01.equals(prRightsAndInterests.getRightsType())) {
                BigDecimal discountRate = Objects.isNull(prRightsAndInterests.getDiscountDays()) ? BigDecimal.ZERO : BigDecimal.valueOf(prRightsAndInterests.getDiscountDays());
                prRightsAndInterests.setDiscountRate(discountRate);
            }
            newTableList.add(prRightsAndInterests);
        }

        List<PrRightsAndInterestsRes> res = BeanMapping.copyList(newTableList, PrRightsAndInterestsRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @CacheEvict(key="'rights_'+#prRightsAndInterestsReq.tenantId+'_'+#prRightsAndInterestsReq.rightsId")
    @Override
    public Integer modifyPrRightsAndInterests(PrRightsAndInterestsReq prRightsAndInterestsReq) throws TxnBizException {
        int res = 0;
        PrRightsAndInterests table = extPrRightsAndInterestsMapper.selectByRightsIdAndTenantId(prRightsAndInterestsReq.getRightsId(),
                prRightsAndInterestsReq.getTenantId());
        if (table == null) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        PrRightsAndInterests prShareProfitTable = BeanMapping.copy(prRightsAndInterestsReq, PrRightsAndInterests.class);
        // 更新
        return res = extPrRightsAndInterestsMapper.updateByRightsIdAndTenantId(prShareProfitTable);
    }

    @CacheEvict(key="'rights_'+#tenantId+'_'+#rightsId")
    @Override
    public Boolean removeByTenantIdAndRightsId(String tenantId, String rightsId) throws TxnBizException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(rightsId)) {
            logger.error("租户id或权益id不可为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        int i = extPrRightsAndInterestsMapper.deleteByRightsIdAndTenantId(rightsId,tenantId);
        return i > 0;
    }

    @Override
    public PrRightsAndInterests getByRightsId(String tenantId, String rightsId) throws TxnBizException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(rightsId)) {
            logger.error("租户ID或权益id为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        PrRightsAndInterests table = extPrRightsAndInterestsMapper.selectByRightsIdAndTenantId(
                rightsId,tenantId);
        return table;
    }

    @Override
    public List<PrRightsAndInterestsRes> getByOrgIdAndTenId(String organizationId, String tenantId) {
        List<PrRightsAndInterests> prVerifyFileTables = extPrRightsAndInterestsMapper.selectByTenIdAndOrgId(organizationId,tenantId);
        return BeanMapping.copyList(prVerifyFileTables, PrRightsAndInterestsRes.class);
    }

    /**
     * 检验权益参数
     *
     * @param tenantId
     * @param rightsId
     * @return
     */
    @Override
    public PrRightsAndInterests checkRightsAndInterests(String tenantId, String rightsId, String productCode) throws TxnBizException {
        PrRightsAndInterests rightsAndInterests = getByRightsId(tenantId, rightsId);
        if (null == rightsAndInterests) {
            logger.error("根据租户号:{}、权益id:{} 查询权益参数表,优惠券查无数据.", tenantId, rightsId);
            throw new TxnBizException(TxnRespCode.COUPON_NOT_EXIST);
        }

        if (!EnableTagEnum.ENABLE.getCode().equals(rightsAndInterests.getEnableTag())) {
            logger.error("优惠券未启用");
            throw new TxnBizException(TxnRespCode.COUPON_NOT_ENABLE);
        }

        if (!rightsAndInterests.getAllowProducts().contains(productCode)) {
            logger.info("请求产品编号:{} 与权益id:{} 适用产品不匹配", productCode, rightsId);
            throw new TxnBizException(TxnRespCode.PRODUCT_CODE_AND_RIGHTS_ID_MISMATCH);
        }

        Integer storeQuantity = rightsAndInterests.getStoreQuantity();
        if(storeQuantity == null || storeQuantity <= 0){
            logger.info("权益id:{} 库存不足，为：{}", rightsId,storeQuantity);
            throw new TxnBizException(TxnRespCode.RIGHTS_AND_INTEREST_STOCK_DEFICIENT);
        }
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String expirationDate = rightsAndInterests.getExpirationDate();
            if (now.after(df.parse(expirationDate))){
                logger.info("当前日期已超过权益失效日期：{}", expirationDate);
                throw new TxnBizException(TxnRespCode.COUPON_EXPIRATION);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return rightsAndInterests;
    }

    @Override
    public int update(PrRightsAndInterests prRightsAndInterests) {
        return extPrRightsAndInterestsMapper.updateByRightsIdAndTenantId(prRightsAndInterests);
    }

    @Override
    public List<PrRightsAndInterestsRes> selectByTenIdAndRightsType(String tenantId, String rightsType) throws TxnException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(rightsType)) {
            logger.error("传入参数为空");
            throw new TxnException(TxnRespCode.NOT_EMPTY);
        }
        List<PrRightsAndInterests> prRightsAndInterestsList = extPrRightsAndInterestsMapper.selectByTenIdIdAndRightsType(tenantId, rightsType);
        return BeanMapping.copyList(prRightsAndInterestsList, PrRightsAndInterestsRes.class);
    }

    @Override
    public void exchangeRightsInterests(String tenantId, String rightsId, int minusStoreQuantity) {
        if (minusStoreQuantity <= 0) {
            throw new RuntimeException("库存扣减必须大于0");
        }

        extPrRightsAndInterestsMapper.exchangeRightsInterests(tenantId, rightsId, minusStoreQuantity);
    }
}
